import { defineStore } from 'pinia';
import { reqLogin, reqUserInfo } from '@/api/user/index';
import { routeList, asyncRouteList, eitherRouteList } from '@/router/routes';
import type { loginForm, loginResponseData, userResponseData } from '@/api/user/type';
import type { UserState } from '../types/type';
//引入深拷贝方法
import cloneDeep from 'lodash/cloneDeep';
import router from '@/router';

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  })
}

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useStoreUser = defineStore('user', {
  state: (): UserState => {
    return {
      token: window.localStorage.getItem('userToken'),
      menuRoutes: routeList,
      username: '',
      avatar: '',
    }
  },
  actions: {
    // 用户登录
    async userLogin(data: loginForm) {
      let result: loginResponseData = await reqLogin(data);
      if (result.code == 200) {
        this.token = (result.data.token as string);
        window.localStorage.setItem('userToken', (result.data.token as string));
        return 'ok';
      } else {
        return Promise.reject(new Error(result.data.message));
      }
    },

    // 获取用户信息
    async userInfo() {
      //获取用户信息进行存储仓库当中[用户头像、名字]
      let result: userResponseData = await reqUserInfo();

      //如果获取用户信息成功，存储一下用户信息
      if (result.code == 200) {
        this.username = (result.data.username as string);
        this.avatar = (result.data.avatar as string);
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRouteList),
          result.data.routes,
        )
        //菜单需要的数据整理完毕
        this.menuRoutes = [...routeList, ...userAsyncRoute, ...eitherRouteList];
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        [...userAsyncRoute, ...eitherRouteList].forEach((route: any) => {
          router.addRoute(route);
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data.message))
      }
    },

    //退出登录
    async userLogout() {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = '';
        this.username = '';
        this.avatar = '';
        window.localStorage.removeItem('userToken');
    },
  },
  getters: {

  }
})